package kjj.android.ch7.app;

import kjj.android.ch7.app.R;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class AndroidServiceActivity extends Activity {
	
	private Button btnStartS; //start service on click
	private Button btnStopS; //stop service on click
	private Button btnBindS;
	
	//declare interface
	private IPerson iPerson;
	//service connection instance
	private ServiceConnection connection = new ServiceConnection() {
		
		@Override
		public void onServiceDisconnected(ComponentName name) {
			// TODO Auto-generated method stub
			
		}
		
		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			// TODO Auto-generated method stub
			iPerson = IPerson.Stub.asInterface(service);
			if (iPerson != null) {
				
				//rpc call
				try {
					iPerson.setAge(111);
					iPerson.setName("Android Nmame");
					
					String msg = iPerson.display();
					//show the message using toast
					Toast.makeText(
							getApplicationContext(), 
							msg, Toast.LENGTH_LONG).show();
				} catch (RemoteException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

				
			}
		}
	};
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        btnStartS = (Button)findViewById(R.id.buttonStartS);
        btnStopS = (Button)findViewById(R.id.buttonStopS);
        
       
        btnStartS.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
			      Intent serviceIntent = new Intent();
			        serviceIntent.setAction("kjj.android.ch7.app.action.MY_SERVICE");
			   
				startService(serviceIntent);
			}
		});
        
        btnStopS.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
			      Intent serviceIntent = new Intent();
			        serviceIntent.setAction("kjj.android.ch7.app.action.MY_SERVICE");
			   
				stopService(serviceIntent);
			}
		});
        
        btnBindS = (Button)findViewById(R.id.buttonBindS);
        btnBindS.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent serviceIntent  = new Intent();
				serviceIntent.setAction(
						"kjj.android.ch7.app.action.MY_REMOTESERVICE");
				bindService(serviceIntent, connection, BIND_AUTO_CREATE);
			}
		});
        
    }
}